<script setup lang='ts'>
import { getHouseList, useBaozuList } from '@fl/api/advertising-api/goods-group'
import { recommendDetail, recommendSave } from '@fl/api/advertising-api/page-config-recommend'
import { SearchTable, SubmitBtn } from '@fl/components'
import { useDicts } from '../../../goods-management//hooks/use-dicts'
import { cloneDeep } from 'lodash-es'

const emits = defineEmits(['refresh'])
const visible = defineModel<boolean>('visible', { required: true })
const id = defineModel<string>('id', { required: false })
const currentSnapshotId = defineModel<number | undefined>('currentSnapshotId', { required: false })
const state = ref<any>()

// const isLoading = ref<boolean>(false)
const isGoodhouseLoading = ref<boolean>(false)
const btnLoading = ref<boolean>(false)
const formRef = ref()
const title = ref<string>('添加')

const { dicts: { PlateType } } = useDicts()
const projectOptions = ref<any>()
const records = ref<any[]>([])
const projectObj = ref<any>() // 选择楼盘后带出来的信息

const houseOptions = ref<any>()
const baozuOptions = ref<any>()
const { data: baozuList } = useBaozuList(visible)

watchEffect(() => {
    title.value = id.value ? '编辑' : '添加'
    console.log('watchEffect', id.value)
    if (id.value) {
        // isLoading.value = true
        // setTimeout(() => {
        //     isLoading.value = false
        // }, 1000)
        recommendDetail({ id: id.value }).then((res) => {
            state.value = {
                ...res,
                plate: String(res.plate),
            }
            console.log('state.value', state.value)
            projectObj.value = {
                projectId: res.projectId,
                projectName: res.projectName,
            }
            setTimeout(() => {
                state.value.recommendIds = res.houseRecommendList.map(item => item.projectId)
            }, 500)
            console.log('state.value', state.value)
        })
    }
    else {
        state.value = {
            plate: '1',
            projectId: '',
            recommendIds: [],
        }
        projectObj.value = {}
    }
})

// 好房列表(新)
function getHouseOptions() {
    isGoodhouseLoading.value = true
    getHouseList().then((res) => {
        houseOptions.value = cloneDeep(res.rows).reduce((pre, cur) => {
            cur.value = cur.projectId
            cur.label = cur.projectName
            pre.push(cur)
            return pre
        }, [])
        isGoodhouseLoading.value = false
    })
    setTimeout(() => {
        isGoodhouseLoading.value = false
    }, 2000)
}
getHouseOptions()

watchEffect(() => {
    if (baozuList.value) {
        const uniqueArray = [...new Map(baozuList.value.rows.map(item => [item.id, item])).values()]
        baozuOptions.value = cloneDeep(uniqueArray).reduce((pre, cur) => {
            cur.value = String(cur.id)
            cur.label = cur.goodsName
            cur.areaName = cur.area
            cur.projectName = cur.goodsName
            pre.push(cur)
            return pre
        }, [])
    }
    if (state.value?.plate === '2') {
        projectOptions.value = baozuOptions.value
    }
    else if (state.value?.plate === '1') {
        projectOptions.value = houseOptions.value
    }
    else {
        projectOptions.value = []
    }

    if (projectOptions.value && state.value?.recommendIds) {
        const indexMap = new Map()
        state.value.recommendIds.forEach((id, index) => {
            indexMap.set(id, index)
        })
        // 先过滤存在的数据，再按recommendIds顺序排序
        records.value = projectOptions.value
            .filter(item => state.value.recommendIds.includes(item.value))
            .sort((a, b) => {
                return indexMap.get(a.value) - indexMap.get(b.value)
            })
    }
})

// 推荐楼盘选择项减少
const filterProjectOptions = computed(() => {
    if (projectOptions.value.length > 0) {
        const arr = projectOptions.value.filter(
            item => item.value !== state.value.projectId,
        )
        return arr
    }
    else {
        return []
    }
})

// 选择楼盘/产品
function projectChange(val) {
    const item = projectOptions.value.find(item => item.value === val)
    projectObj.value = {
        projectId: item.value,
        projectName: item.label,
        areaName: item.areaName,
    }
    state.value.recommendIds = []
}

function plateChange() {
    state.value.recommendIds = []
    state.value.projectId = ''
}

// 推荐楼盘
function recommendIdsChange(val) {
    if (val?.length > 5) {
        ElMessage({
            message: '最多只能选择5个推荐楼盘',
            type: 'warning',
        })
        state.value.recommendIds = val.splice(0, 5)
    }
}

// 提交商品
async function submit(formEl) {
    // const valid = await formRef.value.formInstance.validate()
    const valid = await formEl.validate()
    if (valid) {
        if (valid) {
            const { id, projectName, plate } = state.value
            const params = {
                id,
                projectName,
                plate,
                snapshotId: currentSnapshotId.value,
                ...unref(projectObj),
                houseRecommendList: records.value.map(item => ({
                    // id: item.id,
                    projectId: item.value,
                    projectName: item.projectName,
                    areaName: item.areaName,
                    recommendHouseId: id,
                })),
            }
            console.log('params', params)

            btnLoading.value = true
            recommendSave(params).then(() => {
                ElMessage({
                    message: `${title.value}成功`,
                    type: 'success',
                })
                visible.value = false
                btnLoading.value = false
                emits('refresh', currentSnapshotId.value)
            }).catch(() => {
                btnLoading.value = false
            })
        }
        else {
            console.log('error submit!')
        }
    }
}

function cancel() {
    visible.value = false
    reset()
}

function reset() {
    id.value = ''
    // state.value.recommendIds = []
    projectOptions.value = []
    formRef.value?.resetFields()

    state.value = {
        plate: '1',
        projectId: '',
        recommendIds: [],
    }
}

function getRowIndex(row: any) {
    return records.value.findIndex(
        item => item.projectId === row.projectId,
    )
}

// 检查是否为首项
function isFirst(row: any) {
    return getRowIndex(row) === 0
}

// 检查是否为尾项
function isLast(row: any) {
    return getRowIndex(row) === records.value.length - 1
}

// 上移操作
function moveUp(row: any) {
    const index = getRowIndex(row)
    if (index <= 0)
        return

    const newArray = [...records.value];
    [newArray[index - 1], newArray[index]] = [newArray[index], newArray[index - 1]]
    records.value = newArray
}

// 下移操作
function moveDown(row: any) {
    const index = getRowIndex(row)
    if (index >= records.value.length - 1)
        return

    const newArray = [...records.value];
    [newArray[index], newArray[index + 1]] = [newArray[index + 1], newArray[index]]
    records.value = newArray
}

// 置顶操作
function moveToTop(row: any) {
    const index = getRowIndex(row)
    if (index <= 0)
        return

    const newArray = [...records.value]
    const [movedItem] = newArray.splice(index, 1)
    newArray.unshift(movedItem)
    records.value = newArray
}

// 置底操作
function moveToBottom(row: any) {
    const index = getRowIndex(row)
    if (index >= records.value.length - 1)
        return

    const newArray = [...records.value]
    const [movedItem] = newArray.splice(index, 1)
    newArray.push(movedItem)
    records.value = newArray
}

function deleteConfirm(row) {
    const index = records.value.findIndex(item => item.value === row.projectId)
    if (index !== -1) {
        records.value.splice(index, 1)
        state.value.recommendIds = state.value.recommendIds.filter(id => id !== row.projectId)
    }
    // ElMessageBox.confirm('是否确认删除？', '提示', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning',
    // }).then(() => {
    //     const index = projectOptions.value.findIndex(item => item.value === row.projectId)
    //     if (index !== -1) {
    //         projectOptions.value.splice(index, 1)
    //         state.value.recommendIds = state.value.recommendIds.filter(id => id !== row.projectId)
    //         ElMessage({
    //             message: '删除成功',
    //             type: 'success',
    //         })
    //     }
    // }).catch(() => {
    //     console.log('取消删除')
    // })
}

defineExpose({
    reset,
})

const gridOptions = reactive({
    columns: [
        { field: 'projectName', title: '楼盘名称', width: 200 },
        { field: 'areaName', title: '所在区域', width: 160 },
        { fixed: 'right', slots: { default: 'operate' }, title: '操作', width: 240 },
    ],
})
</script>

<template>
    <PlusDialog v-model="visible"
                :title="title"
                width="800"
                close-on-press-escape
                :has-footer="false"
                @cancel="cancel"
                @closed="reset"
    >
        <div class="mt20">
            <!-- <el-skeleton v-if="isLoading || isBaozuLoading || isGoodhouseLoading"
                         animated
                         height="400"
            /> -->

            <el-form ref="formRef"
                     :model="state"
                     label-width="140"
                     label-position="right"
            >
                <el-form-item label="业务类型："
                              prop="plate"
                              :rules="{
                                  required: true,
                                  message: '请选择业务类型',
                                  trigger: 'change',
                              }"
                >
                    <el-select v-model="state.plate"
                               @change="plateChange"
                    >
                        <el-option v-for="item in PlateType"
                                   :key="item.value"
                                   :value="item.value"
                                   :label="item.label"
                        />
                    </el-select>
                </el-form-item>

                <el-form-item label="楼盘/产品名称："
                              prop="projectId"
                              :rules="{
                                  required: true,
                                  message: '请选择',
                                  trigger: 'change',
                              }"
                >
                    <el-select v-model="state.projectId"
                               filterable
                               @change="projectChange"
                    >
                        <el-option v-for="item in projectOptions"
                                   :key="item.value"
                                   :value="item.value"
                                   :label="item.label"
                        />
                    </el-select>
                </el-form-item>

                <el-form-item label="推荐楼盘/产品："
                              prop="recommendIds"
                              :rules="{
                                  required: true,
                                  message: '请选择',
                                  trigger: 'change',
                              }"
                >
                    <el-select v-model="state.recommendIds"
                               filterable
                               multiple
                               @change="recommendIdsChange"
                    >
                        <el-option v-for="item in filterProjectOptions"
                                   :key="item.value"
                                   :value="item.value"
                                   :label="item.label"
                        />
                    </el-select>

                    <SearchTable ref="tableRef"
                                 v-bind="gridOptions"
                                 :data="records"
                                 :min-height="306"
                    >
                        <!-- <template #plate="row">
                            {{ useDict('PlateType', row.row.plate) }}
                        </template> -->
                        <template #operate="{ row }">
                            <el-button class="small"
                                       type="info"
                                       text
                                       :disabled="isFirst(row)"
                                       @click="moveUp(row)"
                            >
                                上移
                            </el-button>

                            <el-button class="small"
                                       type="info"
                                       text
                                       :disabled="isLast(row)"
                                       @click="moveDown(row)"
                            >
                                下移
                            </el-button>

                            <el-button class="small"
                                       type="info"
                                       text
                                       :disabled="isFirst(row)"
                                       @click="moveToTop(row)"
                            >
                                置顶
                            </el-button>

                            <el-button class="small"
                                       type="info"
                                       text
                                       :disabled="isLast(row)"
                                       @click="moveToBottom(row)"
                            >
                                置底
                            </el-button>

                            <el-button class="small"
                                       text
                                       type="warning"
                                       @click="deleteConfirm(row)"
                            >
                                删除
                            </el-button>
                        </template>
                    </SearchTable>
                </el-form-item>
            </el-form>
        </div>

        <div class="mx-auto mt20 flex justify-center">
            <el-button @click="cancel">
                取消
            </el-button>

            <SubmitBtn type="primary"
                       :loading="btnLoading"
                       @click="submit(formRef)"
            >
                提交
            </SubmitBtn>
        </div>
    </PlusDialog>
</template>

<style lang="scss" scoped>
.material-select-dialog {
    height: 88% !important;

    .el-dialog__body {
        height: 80%;
        overflow-y: auto;
    }
}

.material-img {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.material-img:hover {
    border-color: var(--el-color-primary);
}

.el-icon.material-img-icon {
    font-size: 28px;
    color: #8c939d;
    width: 108px;
    height: 108px;
    text-align: center;
}

.adImg-box {
    width: 108px;
    height: 108px;
    display: flex;
    align-items: center;
    background-color: rgb(0 0 0 / 10%);
    overflow: hidden;
    margin-right: 12px;
}

.json-label {
    display: block;
    width: 100px;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
    word-break: break-all;
    text-align: right;
}
:deep(.small.el-button) {
    padding: 4px;
    margin-left: 6px;
}
</style>
